package com.sltx.util.http;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.quantum.auth.RSA2048;
import com.quantum.dubbo.core.utils.AuthUtils;
import com.sltx.util.CommonUtils;
import com.sltx.util.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Key;
import java.util.Map;

public class IPlatformUtils {

	private static final Logger LOG = LoggerFactory.getLogger(IPlatformUtils.class);
	
	private static Key key = null;

	
	private static final String DC_URL = ConfigUtils.getProperty("datacenter.url", "");
    static String CONIG_FILE_NAME = "thea-key.properties";
	static String uid = CommonUtils.getProperty(CONIG_FILE_NAME,
            "entBigData.uid");
    static String keyPath = CommonUtils.getProperty(CONIG_FILE_NAME,
            SystemUtils.getSystemType());
	
	public static String Auth(String query,String service) throws Exception {

        Gson gson = new Gson();
        //根据关键字查询接口调用
    	Long t1 = System.currentTimeMillis();
    	String params = "{" +
                "         uid:\""+UID+"\"," +
                "         service:\""+service+"\"," +
                "         params:{" +query+
                "         }" +
                "         }";
    	
    	LOG.info("params:"+params);
        //加密过程
        Key key = getKey(keyPath + "public_" + uid + ".key");
//        LOG.info("key:"+key);
        Long ee = System.currentTimeMillis();
        Map<String, Object> map = AuthUtils.encode(params, key);
        Long ss = System.currentTimeMillis();
        LOG.info("参数加密耗时："+(ee-ss)/1000+"s");
        long startTime = System.currentTimeMillis();
        //String result = HttpRequest.sendPost(DC_URL, "uid="+UID+"&data=" + URLEncoder.encode(JSONEncoder.encode(map),"utf-8"));

        String result = HttpRequest.sendPost(DC_URL, "uid="+UID+"&data=" + URLEncoder.encode(gson.toJson(map),"utf-8"));
        result = URLDecoder.decode(result, "UTF-8");
        
        long endTime = System.currentTimeMillis();
        
        LOG.info("调用接口平台所耗时间:"+(endTime-startTime)/1000+"s");
        
        //转换数据
//        LOG.info("result:"+result);
        if(StringUtils.isEmpty(result)){
        	return null;
        }
        long s1 = System.currentTimeMillis();
        //Map<String, Object> resultMap = JSONDecoder.decode(result);
        Map<String, Object> resultMap = gson.fromJson(result,Map.class);
        //解密数据
        try {
            String value = RasAndDesDecode(resultMap);
            long e1 = System.currentTimeMillis();
            LOG.info("数据转换为json，并解密-所耗时间："+(e1-s1)/1000+"s");
            
            Long t2 = System.currentTimeMillis();
            LOG.info("Auth()所耗时间："+(t2-t1)/1000+"s");
            
            return value;
            //得到数据xml
        } catch (Exception ex) {
            //TODO 解密出错，说明返回数据未加密
            //未加密数据只有错误信息，不携带任何数据信息
        }
        return null;
    }

	private static final String UID = ConfigUtils.getProperty("key.uid", "");
	
    /**
     * 解密过程
     *
     * @param data
     * @return
     * @throws Exception
     */
    private static String RasAndDesDecode(Map<String, Object> data) throws Exception {
        return AuthUtils.decode(data, getKey(keyPath + "public_" + uid + ".key"));
    }

    /**
     * 获取公钥
     *
     * @return
     * @throws Exception
     */
    private static Key getKey(String keyPath) throws Exception {
        try {
        	if(key==null){
                //key = RSA2048.getKey(keyPath);
        		URL url = IPlatformUtils.class.getResource("/src/key/" +ConfigUtils.getProperty("key.filename", ""));
        		key = RSA2048.getKey(url.getPath());//密钥路径
        	}
        } catch (Exception ex) {
            throw ex;
        }
        return key;
    }
	
    
    /**
     * 获取共同JSONArray对象
     * @param query
     * @param service
     * @return
     */
    public static JSONObject getInterPlatData(String query,String service){
    	try {
    		Long ss = System.currentTimeMillis();
    		String res = Auth(query,service);
    		Long ee = System.currentTimeMillis();
    		LOG.info("实例化IPlatformUtils，并调用其方法:"+(ee-ss)/1000+"s");
			if(res!=null){
                //JSONObject jsonObject = new JSONObject(res);
				JSONObject jsonObject = new JSONObject();
                JSONObject jsonR = jsonObject.getJSONObject(res);
				return jsonR;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return null;
    }
    
}
